<?php

namespace App\Libs;

/**
 * 苏宁联盟api封装
 * Class SuningLib
 * @package App\Libs
 */
class SuningLib
{
    private $apiUrl = 'https://open.suning.com/api/http/sopRequest/';

    private function formatRequestBody($requestBody)
    {
        if( !is_array($requestBody) || empty($requestBody) ) {
            return '';
        }
        $xml = '';
        foreach ($requestBody as $key => $val) {
            if (is_array($val)) {
                $xml .= "<".$key.">" . $this->formatRequestBody($val) . "</".$key.">";
            } elseif (is_numeric($val)) {
                $xml .= "<".$key.">" . $val . "</".$key.">";
            } elseif (empty($val)) {
                $xml .= "<" . $key . "/>";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }

        $xml .= '';
        return $xml;
    }

    /** 发送请求 */
    public static function curl($url, $postFields = null, $header = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

        // https 请求
        if(strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https"){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            throw new \Exception(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if(200 !== $httpStatusCode){
                throw new \Exception($response, $httpStatusCode);
            }
        }

        curl_close($ch);
        $result = json_decode($response, true)['sn_responseContent'];
        if (isset($result['sn_error'])) {
            return [];
        }

        return $result['sn_body'];
    }

    /** 统一请求 */
    private function currencyRequest($method, $requestBody)
    {
        $requestBodyStr = base64_encode(json_encode($requestBody));
        $appRequestTime = date('Y-m-d H:i:s');
        $format = 'json';
        $versionNo = 'v1.2';
        $appKey = config('lcm.sn_app_key');
        $appSecret = config('lcm.sn_app_secret');
        $data = [
            'appSecret' => $appSecret,
            'appMethod' => $method,
            'appRequestTime' => $appRequestTime,
            'appKey' => $appKey,
            'versionNo' => $versionNo,
            'requestBody' => $requestBodyStr,
        ];
        $sign = '';
        foreach ($data as $value) {
            $sign .= $value;
        }
        $sign = md5($sign);
        $requestHeader = [
            'appMethod: ' . $method,
            'appRequestTime: ' . $appRequestTime,
            'appKey: ' . $appKey,
            'versionNo: ' . $versionNo,
            'format: ' . $format,
            'signInfo: ' . $sign,
        ];
        $result = $this->curl($this->apiUrl . $method, json_encode($requestBody), $requestHeader);
        $methodArr = explode('.', $method);
        $methodIndex = array_pop($methodArr) . ucfirst(array_pop($methodArr));
        if (isset($result[$methodIndex])) {
            return $result[$methodIndex];
        } else {
            return [];
        }
    }

    /** 获取高佣商品类别 */
    public function getInverstmentCategory()
    {
        $requestBody = [
            'sn_request' => [
                'sn_body' => [
                    'queryInverstmentcategoryid' => ''
                ]
            ]
        ];
        $method = 'suning.netalliance.inverstmentcategoryid.query';
        $result = $this->currencyRequest($method, $requestBody);
        if (isset($result['categoryList'])) {
            return $result['categoryList'];
        } else {
            return [];
        }
    }

    /** 高佣商品 */
    public function listInverstmentcommodity($pageIndex, $pageSize)
    {
        $requestBody = [
            'sn_request' => [
                'sn_body' => [
                    'queryInverstmentcommodity' => [
                        'pageIndex' => $pageIndex,
                        'size' => $pageSize
                    ]
                ]
            ]
        ];
        $method = 'suning.netalliance.inverstmentcommodity.query';
        $result = $this->currencyRequest($method, $requestBody);
        return $result;
    }

    /** 关键字搜索 */
    public function searchCommodity($pageIndex, $pageSize = 40, $keyword = '')
    {
        $data = ['pageIndex' => $pageIndex, 'size' => $pageSize];
        if (!empty($keyword)) {
            $data['keyword'] = $keyword;
        }

        $requestBody = [
            'sn_request' => [
                'sn_body' => [
                    'querySearchcommodity' => $data
                ]
            ]
        ];
        $method = 'suning.netalliance.searchcommodity.query';
        $result = $this->currencyRequest($method, $requestBody);
        return $result;
    }
}
